// Copyright 2022 The Molego Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package translate

import (
	"strings"

	utils "gitee.com/west0207/molego/core/utils"

	etree "gitee.com/west0207/etree"
)

// 获取创建索引的Entity标签的sql语句
// dbmsName *string 数据库类型名称，例如：mysql
// createIndexEle *etree.Element 创建索引的Entity标签
func GetCreateIndexSql(dbmsName *string, createIndexEle *etree.Element) (string, error) {
	return getDefaultCreateIndexSql(dbmsName, createIndexEle)
}

// <createIndex indexName="idx_test_property_id_card" tableName="${tableName}" unique="true">
// 		<column name="id_card" type="varchar(150)" />
// </createIndex>
// create index idx_sum_org_code on sum_org (parent_code,org_code);
// create unique index uk_sum_user_account on sum_user (user_account,user_type,org_id);
func getDefaultCreateIndexSql(dbmsName *string, createIndexEle *etree.Element) (string, error) {
	indexName := createIndexEle.SelectAttrValue("indexName", utils.EMPTY)
	SetPropertyValue(dbmsName, &indexName)
	tableName := createIndexEle.SelectAttrValue("tableName", utils.EMPTY)
	SetPropertyValue(dbmsName, &tableName)
	unique := createIndexEle.SelectAttrValue("unique", utils.FALSE)
	if unique == utils.TRUE {
		unique = "unique "
	} else {
		unique = utils.EMPTY
	}
	var builder strings.Builder
	utils.StringAppender(&builder, "create ", unique, "index ", indexName, " on ", tableName, " (")

	columnElements := createIndexEle.SelectElements("column")
	columnLen := len(columnElements)
	builder.Grow(columnLen * utils.ONE_HUNDRED)
	var columnElem *etree.Element
	for i := 0; i < columnLen; i++ {
		columnElem = columnElements[i]
		cname := columnElem.SelectAttrValue("name", utils.EMPTY)
		SetPropertyValue(dbmsName, &cname)
		if i < (columnLen - 1) {
			utils.StringAppender(&builder, cname, utils.COMMA)
		} else {
			utils.StringAppender(&builder, cname)
		}
	}
	utils.StringAppender(&builder, ");", utils.LF)
	return builder.String(), nil
}
